﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Web;
using System.Web.SessionState;
using System.Text;


using iSun.Common;

using iSun.Model;
using iSun.BLL.Base;
using iSun.Entity;

namespace iSun.Web.UI.Controls
{
    public class SaveAction : BaseHandler, IHttpHandler, IRequiresSessionState 
    {
        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            //this.AspCompatMode = true;
            //Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
            //Thread.CurrentThread.IsBackground = false;
            //DateTime dt = DateTime.Now;
            string strAction = this.GetStringFromQueryString("action", "");
            string strEntity = this.GetStringFromQueryString("entity", "");
            string strTable = this.GetStringFromQueryString("table", "");
            string flag = this.GetStringFromQueryString("flag", "");
            string strJson = "";
            if (flag == "1")
            {
                string Forms = ZXContext.Request.Form[0].ToString();
                strJson = Forms;
            }
            else
            {
                strJson = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");
            }

            CreateBussniess(strEntity);
            BaseEntity instance = null;
            try
            {
                instance = (BaseEntity)Globals.JSONtoObject(strEntity, strJson);
            }
            catch { }
            if (instance == null)
            {
                strTable = strEntity;
            }
            if (strTable == "") // 有实体的
            {
                switch (strAction)
                {
                    case "":
                        InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        break;
                    case "insert":
                        InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        break;
                    case "delete":
                        delete(strEntity, strJson);
                        break;
                    case "setRight":
                        SetRight(strJson);
                        break;
                    case "setQuery":
                        SetQuery(strJson);
                        break;
                    case "setTableStruc":
                        SetTableStruc(strJson);
                        break;
                    case "setPhotoCommon":
                        SetPhotoCommon(strJson, GetStringFromQueryString("folder", ""), GetStringFromQueryString("c", "0"));
                        break;
                    case "setDirCommon":
                        SetDirCommon(GetStringFromQueryString("folder", ""), GetStringFromQueryString("c", "0"));
                        break;
                    case "setCoverPage"://设置封面
                        SetDirCoverPage(GetStringFromQueryString("folder", ""), GetStringFromQueryString("c", "0"));
                        break;
                    case "addToF":
                        AddToF(strJson, GetStringFromQueryString("folder", ""));
                        break;
                    case "removeF":
                        removeF(strJson, GetStringFromQueryString("folder", ""));
                        break;
                    case "deleteFile":
                        string path = this.GetStringFromQueryString("path", "");
                        string file = this.GetStringFromQueryString("file", "");
                        DeleteFile(path, file);
                        break;
                    default:
                        InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        break;

                }
            }
            else // 没有实体的
            {
                switch (strAction)
                {

                    case "insert":
                        Insert(strTable, strJson.Replace("[A]", "&"));
                        break;
                    case "update":
                        Update(strTable, strJson.Replace("[A]", "&"));
                        break;
                    case "delete":
                        Delete(strTable, strJson);
                        break;
                }
            }
        }


        #region 方法
        /// <summary>
        /// 设图片为公海
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        /// <param name="folder"></param>
        private void SetPhotoCommon(string strJson, string folder, string c)
        {
            BaseBussnies bll = new BaseBussnies();
            IList<Photo> list = bll.GetEntitysByCondition<Photo>("PhotoDir = '~\\upload\\images\\" + folder + "' and '%" + strJson + "' like '%'+PhotoFileName+'%'");
            if (list == null)
            {
                this.ZXContext.Response.Write("0");
                return;
            }
            if (c == "0")
            {
                foreach (var en in list)
                {
                    bll.entity = en;
                    en.IsCommon = "Y";
                    bll.Update(en);
                }
            }
            else
            {
                foreach (var en in list)
                {
                    bll.entity = en;
                    en.IsCommon = "N";
                    bll.Update(en);
                }
            }
            this.ZXContext.Response.Write("1");
        }


        /// <summary>
        /// 设目录为公海
        /// </summary>
        /// <param name="folder"></param>
        private void SetDirCommon(string folder, string c)
        {
            BaseBussnies bll = new BaseBussnies();
            IList<UserDir> list = bll.GetEntitysByCondition<UserDir>("Dir = '~\\upload\\images\\" + folder + "'");
            if (c == "0")
            {
                foreach (var en in list)
                {
                    bll.entity = en;
                    en.IsCommon = "Y";
                    bll.Update(en);
                }
            }
            else
            {
                foreach (var en in list)
                {
                    bll.entity = en;
                    en.IsCommon = "N";
                    bll.Update(en);
                }
            }
            this.ZXContext.Response.Write("1");
        }

        /// <summary>
        /// 设封面
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="c"></param>
        private void SetDirCoverPage(string folder, string c)
        {
            BaseBussnies bll = new BaseBussnies();
            IList<UserDir> list = bll.GetEntitysByCondition<UserDir>("Dir = '~\\upload\\images\\" + folder + "'");
            //if (c == "0")
            //{
            //    foreach (var en in list)
            //    {
            //        bll.entity = en;
            //        en.IsCommon = "Y";
            //        bll.Update(en);
            //    }
            //}
            //else
            //{
            foreach (var en in list)
            {
                bll.entity = en;
                en.DirCoverPage = c;
                bll.Update(en);
            }
            //}
            this.ZXContext.Response.Write("1");
        }


        /// <summary>
        /// 加入收藏
        /// </summary>
        /// <param name="strJson"></param>
        /// <param name="folder"></param>
        void AddToF(string strJson, string folder)
        {
            BaseBussnies bll = new BaseBussnies();
            //IList<Photo> list = bll.GetEntitys<Photo>("PhotoDir = '~\\upload\\images\\" + folder + "' and '" + strJson + "' like '%'+PhotoFileName+'%'");
            IList<Photo> list = bll.GetEntitysByCondition<Photo>("PhotoDir = '" + folder + "' and '%" + strJson + "' like '%'+PhotoFileName+'%'");
            if (list == null)
            {
                this.ZXContext.Response.Write("0");
                return;
            }

            foreach (var en in list)
            {
                Favorites entity = new Favorites();
                entity.AddUser = this.UserId;
                entity.AddTime = System.DateTime.Now;
                entity.PhotoFileName = en.PhotoFileName;
                entity.PhotoDir = en.PhotoDir;
                entity.PhotoID = en.Oid;

                bll.entity = entity;
                //en.IsCommon = "Y";
                bll.Insert();
            }
            this.ZXContext.Response.Write("1");
        }

        void removeF(string strJson, string folder)
        {
            BaseBussnies bll = new BaseBussnies();
            bll.entity = new Favorites();
            bll.delete(string.Format("PhotoDir='{0}' and PhotoFileName='{1}' and AddUser='{2}'", strJson.Split('|')[0], strJson.Split('|')[1], this.UserId));
            this.ZXContext.Response.Write("1");
        }

        void CreateBussniess(string entityName)
        {
            this._bll = BaseBussnies.CreateInstance(entityName);
        }

        void InsertOrUpdate(string strEntity, string strJson, string action)
        {
            BaseEntity instance = (BaseEntity)Globals.JSONtoObject(strEntity, strJson);
            _bll.entity = instance;
            System.Guid? keyValue = instance.GetKeyFieldValue();
            //BaseEntity item = instance.
            //数据验证
            string strMsg = instance.CheckData();
            if (strMsg != "")
            {
                HttpContext.Current.Response.Write(strMsg);
                return;
            }
            strMsg = instance.GetDataCheckMessage();
            if (strMsg != "")
            {
                HttpContext.Current.Response.Write(strMsg);
                return;
            }

            //BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(instance);
            string checkResult = _bll.CheckData();
            if (false == string.IsNullOrEmpty(checkResult))
            {
                HttpContext.Current.Response.Write(checkResult);
                return;
            }
            bool b = false;
            if (action == "")
            {
                if (instance.GetKeyFieldValue() == new System.Guid())
                {
                    action = "insert";
                }
            }
            //instance.Save();
            if (action == "insert")
            {
                if (null == (Globals.GetPropertyValue(instance, "AddUser") as Guid?) || (Globals.GetPropertyValue(instance, "AddUser") as Guid?) == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                    Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);
                }
                if (EntityName == "PhotoDetail")
                {
                    //Photo photo = _bll.GetEntityById(((PhotoDetail)instance).Oid.ToString()) as Photo;
                    //ZX.Common.IPTC.ReadImageInfo.SetIptc(Server.MapPath(photo.PhotoDir) + "\\" + photo.PhotoFileName, ((PhotoDetail)instance));
                }
                //_bll.get
                b = _bll.Insert();

                if (EntityName == "SysTable")
                {
                    BLL.Base.DBTable dbTable = SqlDBTable.Instance;
                    dbTable.CreateTable((instance as SysTable).TableName);
                }
            }
            else
            {
                if (EntityName == "PhotoDetail")
                {
                    try
                    {
                        _bll.entity = new Photo();
                        Photo photo = _bll.GetEntityById(((PhotoDetail)instance).Oid.ToString()) as Photo;
                       // iSun.Common.IPTC.ReadImageInfo.WriteMetadata(ZXContext.Server.MapPath(photo.PhotoDir) + "\\" + photo.PhotoFileName, ((PhotoDetail)instance));
                    }
                    catch { };
                }
                _bll.entity = instance;
                try
                {

                    b = _bll.Update();
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write(e.Message);
                }
            }
            if (b)
            {
                HttpContext.Current.Response.Write("1");
            }
            else
            {
                HttpContext.Current.Response.Write("0");
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        void delete(string strEntity, string strJson)
        {
            BaseEntity instance = (BaseEntity)iSun.Common.Reflection.CreateEntitysInstance(strEntity);
            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(instance);
            string key = instance.getKey();
            if (string.IsNullOrEmpty(strJson))
            {
                strJson = this.GetStringFromQueryString("id", "");
                bll.Delete(key + "='" + strJson + "'");
                HttpContext.Current.Response.Write("1");
            }
            else
            {
                string[] strarr = strJson.Split(',');
                foreach (var s in strarr)
                {
                    bll.Delete(key + "='" + s + "'");
                }
                HttpContext.Current.Response.Write("1");
            }
        }

        /// <summary>
        /// 设置权限
        /// </summary>
        /// <param name="strJson"></param>
        void SetRight(string strJson)
        {
            var list = (List<V_FunctionRight>)Globals.JSonToObject<List<V_FunctionRight>>(strJson);
            string strSql = "update SysRoleFunction set BarItems='{0}',OperateRangeType='{2}',Depts='{3}',Condition='{4}' where RoleFunctionID='{1}'\n";
            StringBuilder sSql = new StringBuilder("");
            foreach (var item in list)
            {
                sSql.Append(string.Format(strSql, item.BarItem, item.RoleFunctionID, item.OperateRangeType, item.Depts, item.Condition));
            }
            BaseBussnies bll = new BaseBussnies();
            if (sSql.ToString() == "")
            {
                ZXContext.Response.Write("没有数据!");
                return;
            }
            int i = bll.RunSqlCommand(sSql.ToString());
            if (i > 0)
            {
                ZXContext.Response.Write("1");
            }
            else
            {
                //写日志
                WriteExpLog();
                ZXContext.Response.Write("0");
            }
        }


        void SetUserRight(string strJson)
        {

        }
        /// <summary>
        /// 设置表结构
        /// </summary>
        /// <param name="strJson"></param>
        /// <summary>
        /// 设置表结构
        /// </summary>
        /// <param name="strJson"></param>
        void SetTableStruc(string strJson)
        {
            List<SysTableField> list = Globals.JSonToObject<List<SysTableField>>(strJson);
            BLL.Base.DBTable dbTable = SqlDBTable.Instance;
            foreach (SysTableField entity in list)
            {
                if (entity.TableFieldID == Guid.Empty)
                {
                    string strFiled = entity.FiledType;
                    switch (strFiled.ToLower())
                    {
                        case "varchar":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "nvarchar":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "char":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "nchar":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "ntext":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;

                        case "bigint":
                            strFiled = entity.FiledType;
                            break;
                        case "int":
                            strFiled = entity.FiledType;
                            break;
                        case "bit":
                            strFiled = entity.FiledType;
                            break;
                        case "datetime":
                            strFiled = entity.FiledType;
                            break;
                        case "smalldatetime":
                            strFiled = entity.FiledType;
                            break;
                        case "date":
                            strFiled = entity.FiledType;
                            break;
                        case "uniqueidentifier":
                            strFiled = entity.FiledType;
                            break;
                        case "money":
                            strFiled = entity.FiledType;
                            break;

                        case "binary":
                            strFiled = entity.FiledType;
                            break;
                        case "float":
                            strFiled = entity.FiledType;
                            break;
                        case "image":
                            strFiled = entity.FiledType;
                            break;
                        case "numeric":
                            strFiled = entity.FiledType + "(" + entity.Length + ")";
                            break;
                        case "real":
                            strFiled = entity.FiledType;
                            break;
                        default:
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;

                    }


                    dbTable.AddCol(entity.TableName, entity.FieldName, strFiled);
                    dbTable.AddColNotes(entity.TableName, entity.FieldName, entity.Notes);
                }

            }
            ZXContext.Response.Write("1");
        }


        /// <summary>
        /// 创建表
        /// </summary>
        /// <param name="TableName"></param>
        void SetTable(string TableName)
        {
            BLL.Base.DBTable dbTable = SqlDBTable.Instance;
            dbTable.CreateTable(TableName);
        }

        /// <summary>
        /// 设置查询
        /// </summary>
        /// <param name="strJson"></param>
        void SetQuery(string strJson)
        {
            QuerySolution entity = (QuerySolution)Globals.JSonToObject<QuerySolution>(strJson);
            entity.BaseEntityState = WorkState.New;
            entity.EntityName = this.EntityName;
            entity.FunctionID = this.FunctionID;
            entity.AddUser = this.UserId;
            entity.AddTime = DateTime.Now;
            string action = "";

            if (entity.QueryId == null || entity.QueryId == Guid.Empty)
            {
                action = "insert";
                entity.QueryId = Guid.Empty;
            }

            //BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            if (entity.IsDefault == "Y")
            {
                _bll.RunSqlCommand("update Set_QuerySolution set IsDefault='N' where AddUser='" + this.UserId + "' and FunctionID='" + entity.FunctionID + "'");
            }
            bool b;
            if (action == "insert")
            {

                b = _bll.Insert();
            }
            else
            {
                b = _bll.Update();
            }
            if (b)
            {
               this.ZXContext.Response.Write("1");
            }
            else
            {
                this.ZXContext.Response.Write("0");
            }
        }

        private void DeleteFile(string FilePath, string File)
        {
            string path = this.ZXContext.Server.MapPath(FilePath);
            System.IO.File.Delete(path + File);
        }


        #region No Entity
        public void Insert(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.TableKey = strArrary[0];
                instance.KeyType = strArrary[1];
            }
            instance.CreateDataTable();
            instance.EntityJson = json;// ZX.Common.Globals.DataRowToJSON(instance.DRow);
            instance.FieldValue = iSun.Common.Globals.ConvertToDictionary(instance.EntityJson);
            instance.SetValue(instance.FieldValue);

            BaseBussnies bll = new BaseBussnies(instance);
            if (bll.Insert())
            {
                ZXContext.Response.Write("1");
            }
        }

        public void Update(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.TableKey = strArrary[0];
                instance.KeyType = strArrary[1];
            }
            instance.CreateDataTable();
            instance.EntityJson = json;// ZX.Common.Globals.DataRowToJSON(instance.DRow);
            instance.FieldValue = iSun.Common.Globals.ConvertToDictionary(instance.EntityJson);
            instance.SetValue(instance.FieldValue);

            BaseBussnies bll = new BaseBussnies(instance);
            if (bll.Update())
            {
                ZXContext.Response.Write("1");
            }
        }

        public void Delete(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.TableKey = strArrary[0];
                instance.KeyType = strArrary[1];
            }
            string[] ids = json.Split(',');
            try
            {
                foreach (string id in ids)
                {
                    instance.Delete(id);
                }
                ZXContext.Response.Write("1");
            }
            catch (Exception e)
            {
                ZXContext.Response.Write(e.Message);
            }
        }
        #endregion
        #endregion
    }
}
